// delay for given number of microseconds (use 22-65535) or milliseconds (1-65535) using timer 0
// delayT0_us minimum is 22 us
// (C) Copyright 2009, 2010 Communications Programming, Inc.

#include "userLib.h"
#include "timers.h"

void delayT0_init()					// init timer for first use
{
	T0CON = T0CON_VAL;				// timer on, set prescale 
}

void delayT0_us( uint16 us )		// delay a given number of microseconds
{
	WriteTimer0(0);
	us *= timer_ticks_per_microsec;
	if( us >= DELAY_OVERHEAD_TICKS )
	{
		us -= DELAY_OVERHEAD_TICKS;

		// this is an 8-bit timer, so break total ticks into 
		// 255-tick chunks 
		while( us > 255 )
		{
			while( ReadTimer0() < 170 )	// < 255 to compensate for loop overhead
			{}
			us -= 255;
			WriteTimer0(0);
		}	
		while( ReadTimer0() < us )
		{}
	}	
}

void delayT0_ms( uint16 ms )		// delay a given number of milliseconds (1-65535)
{
	while( ms-- )
	{
		delayT0_us(1000);
	}
}

